package apis

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"net/http"
	"strconv"
	"strings"
	"tuowei.com/app/api/models"
	"tuowei.com/app/api/service"
	"tuowei.com/app/api/service/dto"
	"tuowei.com/pkg/xlog"
)

type ApiTestRecord struct {
	api.Api
	Base
}

func (e ApiTestRecord) MockExaminationList(c *gin.Context) {

	s := service.ApiTestRecord{}
	err := e.MakeContext(c).
		MakeOrm().
		MakeService(&s.Service).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	err, studentId := e.GetUser(&e.Api)
	if err != nil {
		xlog.Error(err)
		e.Error(401, err, err.Error())
		return
	}

	var model models.SysPracticeRecord
	var examinationModel models.SysExamination
	var list []*models.PracticesRecordList
	err = e.Orm.Table(model.TableName()+" as spr").
		Order("spr.id desc").
		Joins(" left join "+examinationModel.TableName()+" as sex on spr.obj_id = sex.id").
		Select("spr.id,sex.count,sex.name,spr.obj_id,spr.ex_type,spr.correct_count,spr.error_count").
		Where("spr.ex_type = ?", 3).
		Where("spr.student_id = ?", studentId).Scan(&list).Error
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	for k, v := range list {
		if v.Count == 0 {
			list[k].CorrectRate = strconv.Itoa(0) + "%"
		} else {
			list[k].CorrectRate = fmt.Sprintf("%0.2f", float64(v.CorrectCount)/float64(v.Count)*100) + "%"
		}
	}
	e.OK(list, "success")
	return
}

type practice struct {
	Count  int
	Status int
}

func (e ApiTestRecord) PracticeRecordList(c *gin.Context) {
	req := dto.SysErrRecordGetPageReq{}
	s := service.ApiTestRecord{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Default(c.Request.Method, c.ContentType())).
		MakeService(&s.Service).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	err, studentID := e.GetUser(&e.Api)
	if err != nil {
		xlog.Error(err)
		e.Error(401, err, err.Error())
		return
	}
	//获取该学员的错题记录
	var errRecordModel models.SysExerciseRecord
	var list []*models.ErrorRecordList
	var count int64
	//var trueCount int64
	var falseCount int64
	session := e.Orm.Model(errRecordModel)
	if strings.Trim(req.SubjectType, " ") != "" {
		session.Where("subject_type = ?", req.SubjectType)
	}
	practiceObjs := make([]practice, 0)
	err = session.Where("student_id = ?", studentID).Select("count(id) as count,status").Group("status").Find(&practiceObjs).Error
	if err != nil {
		e.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	for _, v := range practiceObjs {
		count += int64(v.Count)
		if v.Status == 0 {
			falseCount += int64(v.Count)
		}
	}
	rate := float64(0)
	if count == 0 {
		rate = 0
	} else {
		rate = (float64(falseCount) / float64(count)) * 100
	}

	if req.PageIndex == 0 {
		req.PageIndex = 1
	}

	if req.PageSize == 0 {
		req.PageSize = 20
	}

	// 看球不懂这个sql。。写的是个啥。。
	sql := "select * from (select * from sys_exercise_record where 1 "
	if strings.Trim(req.SubjectType, " ") != "" {
		sql += " AND subject_type = '" + req.SubjectType + "'"
	}
	sql += " AND status = 0) as er left join sys_question_bank as sqb on  er.ex_id = sqb.id "
	sql += fmt.Sprintf(" where er.student_id = %d order by er.id desc limit %d , %d", studentID, (req.PageIndex-1)*req.PageSize, req.PageSize)
	err = e.Orm.Raw(sql).Scan(&list).Error
	//err = e.Orm.Raw("select * from (select * from sys_exercise_record where subject_type = ? and status = 0) as er"+
	//	" left join sys_question_bank as sqb on  er.ex_id = sqb.id where er.student_id = ? order by er.id desc limit ? , ?", req.SubjectType, studentID, (req.PageIndex-1)*req.PageSize, req.PageSize).Scan(&list).Error
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	courseIdArr := make([]int, 0)
	questionBankArr := make([]int, 0)
	examinationArr := make([]int, 0)
	for _, values := range list {
		switch req.ExerciseType {
		case 1:
			courseIdArr = append(courseIdArr, values.LinkId)
		case 2:
			questionBankArr = append(questionBankArr, values.LinkId)
		case 3:
			examinationArr = append(examinationArr, values.LinkId)
		}
	}
	courseTmpList := make([]*models.CourseList, 0)
	exercisesTmpList := make([]*models.SysExercisesList, 0)
	examinationTmpList := make([]*models.ExaminationList, 0)
	switch req.ExerciseType {
	case 1:
		var model models.SysCourse

		err = e.Orm.Model(model).Where("course_id in ?", courseIdArr).Find(&courseTmpList).Error
		if err != nil {
			xlog.Error(err)
			e.Error(500, err, err.Error())
			return
		}
	case 2:
		var model models.SysExercisesList
		err = e.Orm.Model(model).Where("id in ?", questionBankArr).Find(&exercisesTmpList).Error
		if err != nil {
			xlog.Error(err)
			e.Error(500, err, err.Error())
			return
		}
	case 3:
		var model models.ExaminationList
		err = e.Orm.Model(model).Where("id in ?", examinationArr).Find(&examinationTmpList).Error
		if err != nil {
			xlog.Error(err)
			e.Error(500, err, err.Error())
			return
		}

	}

	for _, v := range list {
		if v.ExType == 1 {
			for _, vs := range courseTmpList {
				if vs.CourseId == v.LinkId {
					v.LinkTitle = vs.Name
				}
			}
			//v.LinkTitle = courseTmpList[v.LinkId].Name
		} else if v.ExType == 2 {
			for _, vs := range exercisesTmpList {
				if vs.Model.Id == v.LinkId {
					v.LinkTitle = vs.Name
				}
			}
		} else if v.ExType == 3 {
			for _, vs := range examinationTmpList {
				if vs.Model.Id == v.LinkId {
					v.LinkTitle = vs.Name
				}
			}
		}
	}

	e.OK(gin.H{"sumCount": count, "pageIndex": 1, "pageSize": 10, "falseCount": falseCount, "rate": fmt.Sprintf("%0.2f", rate), "list": list}, "Success")
	return

}
